
//线程不安全
class counter
{
    public int count=0;
//    public  void add()
//    {
//        //加锁
//        synchronized (this)
//        {
//            count++;
//        }
//
//    }
    synchronized public void add()
    {

        count++;
    }
    public  int get()
    {

        return  count;
    }
}
public class ThreadDemo6 {
    public static void main(String[] args) throws InterruptedException {
        counter counter=new counter();
        //创建两个线程,让这两个线程全部自增5W次
        Thread t1=new Thread(() ->{
            for (int i = 0; i < 10000; i++) {
                counter.add();
            }
        });
        Thread t2=new Thread(() ->{
            for (int i = 0; i < 10000; i++) {
                counter.add();
            }
        });

        t1.start();
        t2.start();

        //等待两个线程全部结束,查看结果
        t1.join();
        t2.join();
        System.out.println(counter.get());
    }
}
